package main

import (
	"context"
	"fmt"
	"google.golang.org/grpc"
	"sale_system/user_srv/proto"
	"strconv"
)

var client proto.UserClient
var conn *grpc.ClientConn

func Init() {
	var err error
	
	conn, err = grpc.Dial("127.0.0.1:8899", grpc.WithInsecure())
	if err != nil {
		panic("failed to connect, " + err.Error())
	}

	client = proto.NewUserClient(conn)
}

// TestGetUserListAndVerifyPassword 测试获取用户列表和校验用户密码接口
func TestGetUserListAndVerifyPassword() {

	rsp, err := client.GetUserList(context.Background(), &proto.PageInfoRequest{Pn: 1, PSize: 8})

	if err != nil {
		panic("failed to call GetUserList(), " + err.Error())
	}

	i := 0 // i为 Pn - 1
	for _, user := range rsp.Data {

		fmt.Println(user)
		verifyRsp, err := client.VerifyPassword(context.Background(), &proto.VerifyRequest{
			Password:          "123456-" + strconv.Itoa(i), // 需要自己设定
			EncryptedPassword: user.Password,
		})
		i++
		if err != nil {
			panic("failed to call VerifyPassword, " + err.Error())
		}
		fmt.Println(verifyRsp.Success)
	}
}
func TestCreateUser() {

	//for i := 0; i < 10; i++ {
	//	rsp, err := test.CreateUser(context.Background(), &proto.CreateUserRequest{
	//		NickName: fmt.Sprintf("user-%d", i),
	//		Password: "123456-" + strconv.Itoa(i),
	//		Phone:    "1788073071" + strconv.Itoa(i),
	//	})
	//	if err != nil {
	//		panic("failed to call CreateUser, " + err.Error())
	//	}
	//	fmt.Println(rsp)
	//}

	_, _ = client.CreateUser(context.Background(), &proto.CreateUserRequest{
		NickName: "这个用户的密码是123456",
		Password: "123456",
		Phone:    "13147065653",
	})
}
func TestGetUserById() {

	rsp, err := client.GerUserById(context.Background(), &proto.IdRequest{
		Id: 10,
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(rsp)
}
func TestGetUserByPhone() {
	rsp, err := client.GerUserByPhone(context.Background(), &proto.PhoneRequest{
		Phone: "13147065653",
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(rsp)
}

func TestUpdateUser() {

	_, err := client.UpdateUser(context.Background(), &proto.UpdateUserRequest{
		NickName: "user-change",
		Id:       11,
		Birthday: 9992,
		Gender:   "female",
	})

	if err != nil {
		panic(err)
	}
}

func main() {

	Init()
	defer conn.Close()
	//TestCreateUser()
	//TestGetUserListAndVerifyPassword()
	TestGetUserById()
	//TestGetUserByPhone()
	//TestUpdateUser()
}
